﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TPA.DataAccess;
using System.Threading;


namespace TVProgramAnalyst.TimeLine
{
    public partial class frmProgressBar : Form
    {
        public string WorkingText
        {
            get; //{ return lblWorkingText.Text; }
            set;// { lblWorkingText.Text = value; }
        }

        public List<KeyPoint> ProgramLog { get; set; }
        public List<KeyPoint> AdvertisementLog { get; set; }
        
        public frmProgressBar()
        {
            InitializeComponent();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (WorkingText == "正在保存时间线......")
                SaveTimeline(TPAProgram._TimeLine);
            else
                CombineTimeline(ProgramLog, AdvertisementLog);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pb1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Cursor = Cursors.Arrow;
            this.Dispose(true);
        }

        #region Save timeline to database
        //save time line
        //every program should be in database (existingprograms) now. if not exception will be throw out.
        private void SaveTimeline(List<KeyPoint> timeline)
        {
            //bool overwrite = false;
            
           IList<KeyPoint> existingchannelanddaterecord =
                (from kp in timeline
                group kp by new { kp.Date, kp.Channel } into kpg
                select kpg.FirstOrDefault()).ToList();
            //int totalWork = existingchannelanddaterecord.Count();
            //string lable = WorkingText;
            SetText( "检查已有记录......");
            for (int i = 0; i < existingchannelanddaterecord.Count(); i++ )
            {
                KeyPoint kp = existingchannelanddaterecord.ElementAt(i);
                BLLFactory.TimeLineBLL.DeleteByChannelNameandDate(kp.Channel, kp.Date);
                //int milliSecondsToWait = 1;
                //System.Threading.Thread.Sleep(milliSecondsToWait);
                //int progress = i * 100 / totalWork;
                //backgroundWorker1.ReportProgress(progress);
            }
            //BLLFactory.TimeLineBLL.SaveChanges();
            //BLLFactory.TimeLineBLL.Refresh();
            SetText(WorkingText); 
            int totalWork = timeline.Count;
            for (int i = 0; i < timeline.Count;i++ )
            {
                KeyPoint kp = timeline[i];
                Program program = TPAProgram._ExistingPrograms.Single(p => p.Name == kp.Label);
                if (program != null)
                {
                    TimelineSegment td = Helper.TimelineHelper.ConvertToTimelineSegment(kp, program);
                    //if (CheckExistingRecord)
                    //{
                    //    if (BLLFactory.TimeLineBLL.IsExist(td))
                    //    {
                    //        BLLFactory.TimeLineBLL.Remove(td);
                    //    }
                    //}
                    BLLFactory.TimeLineBLL.Add(td);
                    try
                    {
                        BLLFactory.TimeLineBLL.SaveChanges();
                    }
                    catch (Exception tpaex)
                    {
                        TPAProgram.LastError = tpaex.Message;
                        MessageBox.Show(TPAProgram.LastError+"\n\r"+td.ChannelName+","+td.Program.Name+","+td.StartDateTime);
                        //BLLFactory.TimeLineBLL.Refresh();
                        //this.Dispose(true);
                        return;
                    }
                }
                else
                {
                    throw new TPAException() { Source = "missing program: " + kp.Label };
                }
                int milliSecondsToWait = 1;
                System.Threading.Thread.Sleep(milliSecondsToWait);

                int progress = i * 100 / totalWork;
                if (progress > pb1.Value)
                {
                    SetText("正在保存\"" + kp.Channel + "\"时间线......");
                    backgroundWorker1.ReportProgress(progress);
                }
            }
            //lblNewPrograms.Text = TPAProgram._NewPrograms.Count.ToString();
            //lbltimelineitem.Text = timeline.Count.ToString();
        }
        #endregion

        #region Combine Timeline
        /// <summary>
        /// Combine _ProgramLog and _AdvertisementLog to _Timeline
        /// </summary>
        private void CombineTimeline(List<KeyPoint> _ProgramLog, List<KeyPoint> _AdvertisementLog)
        {
            List<KeyPoint> timeline = new List<KeyPoint>();
            int totalWork = _ProgramLog.Count + _AdvertisementLog.Count;
            for (int pindex = 0, aindex = 0; pindex < _ProgramLog.Count || aindex < _AdvertisementLog.Count; )
            {
                KeyPoint currentP = null, currentA = null;
                if (pindex < _ProgramLog.Count)
                {
                    currentP = _ProgramLog[pindex];
                }
                if (aindex < _AdvertisementLog.Count)
                {
                    currentA = _AdvertisementLog[aindex];
                }
                if (currentA != null && currentP != null)
                {
                    if (currentP.DateTimeIn < currentA.DateTimeIn)
                    {
                        //Add current program to timeline;
                        Helper.TimelineHelper.JoinKeyPoint(timeline, currentP);
                        pindex++;
                    }
                    else
                    {
                        //add current advertisement to timeline;
                        Helper.TimelineHelper.JoinKeyPoint(timeline, currentA);
                        aindex++;
                    }
                }
                else if (currentA != null)
                {
                    Helper.TimelineHelper.JoinKeyPoint(timeline, currentA);
                    aindex++;
                }
                else if (currentP != null)
                {
                    Helper.TimelineHelper.JoinKeyPoint(timeline, currentP);
                    pindex++;
                }
                //lblTotalTime.Text = totaltime.
                int milliSecondsToWait = 1;
                System.Threading.Thread.Sleep(milliSecondsToWait);

                int progress = (pindex+aindex) * 100 / totalWork;
                if (progress > pb1.Value)
                {
                    SetText( "正在合并\"" + currentP.Channel + "\"时间线......");
                    backgroundWorker1.ReportProgress(progress);
                }
            }
            //dataGridView3.DataSource = TPAProgram._TimeLine;
            TPAProgram._TimeLine.AddRange(timeline);
        }
        #endregion


        private void frmProgressBar_Load(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            backgroundWorker1.RunWorkerAsync();
        }

        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.lblWorkingText.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.lblWorkingText.Text = text;
            }
        }

        delegate void SetTextCallback(string text);


    }
}
